#include"mystdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
 
 
//创建对应文件的Myfile结构体对象
static Myfile* BuyMyfile(int flag,int fd)
{
    Myfile* f=(Myfile*)malloc(sizeof(Myfile));
    if(f==NULL)return NULL;
    f->fileno=fd;
    f->flag=flag;
    f->bufferlen=0;
    f->flush_method=LINE_FLUSH;
    memset(f->outbuffer,0,sizeof(f->outbuffer));
 
    return f;
}
 
 
//打开文件
Myfile* MyFopen(const char* path,const char* mode)
{
    int fd=-1;
    int flag=0;
    //写方式
    if(strcmp(mode,"w")==0)
    {
        flag=O_WRONLY |O_CREAT |O_TRUNC;
        fd=open(path,flag,0666);
    }
    //读方式
    else if(strcmp(mode,"r")==0)
    {
        flag=O_RDONLY;
        fd=open(path,flag);
    }
    //追加方式
    else if(strcmp(mode,"a")==0)
    {
        flag=O_WRONLY | O_CREAT | O_APPEND;
        fd=open(path,flag,0666);
    }
    else{
        //....
        
    }
return BuyMyfile(flag,fd);
 
}
 
 
//关闭文件
void MyFclose(Myfile* file)
{
    if(file->fileno<0)return;
    MyFFlush(file);
    close(file->fileno);
    //释放Myfile结构体对象内存
    free(file);
 
}
 
 
//向文件内写入
size_t MyFwrite(Myfile* file,void *str,int len)
{
    //将str数据拷贝到缓冲区当中
    memcpy(file->outbuffer+file->bufferlen,str,len);
    file->bufferlen+=len;
    //判断是否满足刷新的条件：刷新条件为行刷新且当前缓冲区当中内容以\n结尾
    if((file->flush_method & LINE_FLUSH) && file->outbuffer[(file->bufferlen)-1]=='\n' ){
        MyFFlush(file);
    }
    return len;
 
}
 
//刷新缓冲区
void MyFFlush(Myfile* file)
{
    if(file->bufferlen<0)return;
    //使用系统调用将缓冲区当中的数据写入到文件内核缓冲区当中
    int n=write(file->fileno,file->outbuffer,file->bufferlen);
    (void)n;
    //将文件缓冲区当中的数据强制同步到文件当中
    fsync(file->fileno);
    file->bufferlen=0;
}
 
